package com.woniu.park.controller;


import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.config.AlipayConfig;
import com.woniu.park.entity.Order;
import com.woniu.park.entity.Parkspace;
import com.woniu.park.entity.User;
import com.woniu.park.controller.form.TransferInfoForm;
import com.woniu.park.service.IOrderService;
import com.woniu.park.service.ITransferInfoService;
import com.woniu.park.util.Status;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author cxb
 * @since 2020-09-08
 */
@RestController
//@RequestMapping("/park/transfer-info")
@Slf4j
public class TransferInfoController {
    @Autowired
    private ITransferInfoService transferService;
    @Autowired
    private IOrderService orderService;

    @RequestMapping("payMoney")
    public void Pay(String money, String type,String parkspaceId,Integer stoppingTime, HttpServletRequest request, HttpServletResponse response, HttpSession session){
//        String money = request.getParameter("money");
        //UserId TransferInfoMoney ParkspaceId StoppingTime OrderId
        double parseMoney = Double.parseDouble(money);
        User userSession = (User)session.getAttribute("user");
        int userId=userSession.getUserId();
        System.out.println("userId:"+userId);
//        int userId=1;
        try {
            int orderId=0;

            //生成订单
            if (type.equals("2")) {
                //生成订单并将该车为状态改为已预约
                orderId =orderService.insertOrder(userId,parseMoney,parkspaceId,stoppingTime);

            }
            //新增一条交易流水记录
            int id = transferService.insertTransfer(userId, parseMoney,orderId);
            //获得初始化的AlipayClient
            AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

            //设置请求参数
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            alipayRequest.setReturnUrl(AlipayConfig.return_url);
            alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

            //商户订单号，商户网站订单系统中唯一订单号，必填
            String out_trade_no = id+"";
            //付款金额，必填

            String total_amount = money;
            //订单名称，必填
            String subject =null;
            if (type.equals("1")) {
                subject = Status.PAY_ADDMONRY;
            }else if (type.equals("2")){
                subject = Status.PAY_PAYMONRY;
            }

            //商品描述，可空
            String body = orderId+"";
            String cid = userId+"";
            String passback_params = new String(cid.toString());
            String str = URLEncoder.encode(passback_params,"UTF-8");


            alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                    + "\"total_amount\":\""+ total_amount +"\","
                    + "\"subject\":\""+ subject +"\","
                    + "\"body\":\""+ body +"\","
                    + "\"passback_params\":\""+str+"\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

            //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
            //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
            //		+ "\"total_amount\":\""+ total_amount +"\","
            //		+ "\"subject\":\""+ subject +"\","
            //		+ "\"body\":\""+ body +"\","
            //		+ "\"timeout_express\":\"10m\","
            //		+
            //"\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
            //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

            //请求

            //输出
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            String result = alipayClient.pageExecute(alipayRequest).getBody();
            System.out.println(out_trade_no);
            out.println(result);
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }

    @RequestMapping("updateTransfer")
    public void updateTransfer(HttpServletRequest request, HttpServletResponse response){
//        System.out.println("进入updateTransfer");
        // 获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified;
        try {
//            System.out.println("开始验证");
            signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset,
                    AlipayConfig.sign_type);

            if (signVerified) {// 验证成功
                // 商户订单号
                String out_trade_no = request.getParameter("out_trade_no");

                // 支付宝交易号
                String trade_no = request.getParameter("trade_no");
                //订单名称
                String subject = request.getParameter("subject");
                //订单金额
                String money = request.getParameter("total_amount");
                System.out.println(money);
                // 交易状态
                String trade_status = request.getParameter("trade_status");
                System.out.println("trade_status:"+trade_status);
                String passback_params = request.getParameter("passback_params");
                String orderId = request.getParameter("body");
                System.out.println("orderId"+orderId);
                System.out.println("passback_params:"+passback_params);
                String cidPar = URLDecoder.decode(passback_params,"UTF-8");
                int userId =Integer.parseInt(cidPar);
//                System.out.println("cid："+cid);
//                System.out.println("out_trade_no："+out_trade_no);
                if (trade_status.equals("TRADE_SUCCESS")) {
                    try {
                        System.out.println("进入");
                        //int id, String trade_no, String subject,int userId,double money
                        TransferInfoForm transferInfoForm=new TransferInfoForm();
                        transferInfoForm.setTradeNo(trade_no);
                        transferInfoForm.setSubject(subject);
                        transferInfoForm.setTransferInfoMoney(Double.parseDouble(money));
                        transferInfoForm.setTransferInfoId(Integer.parseInt(out_trade_no));
                        transferInfoForm.setTransferInfoUserId(userId);
                        transferInfoForm.setTransferOrderId(Integer.parseInt(orderId));
//                        Integer.parseInt(out_trade_no),trade_no,subject,userId,Double.parseDouble(money)
                        transferService.updateTransfer(transferInfoForm);

                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }

            }



        } catch (AlipayApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}

